package com.sq.partner.manager.controller;

import java.sql.Struct;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.common.exception.AppException;
import com.sq.partner.manager.mybatis.model.CoreDept;
import com.sq.partner.manager.mybatis.model.DeptDto;
import com.sq.partner.manager.mybatis.model.GatewayRole;
import com.sq.partner.manager.mybatis.model.GatewayRoleDept;
import com.sq.partner.manager.mybatis.model.GatewayRoleMenu;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.mybatis.model.GatewayUserRole;
import com.sq.partner.manager.mybatis.model.TreeDto;
import com.sq.partner.manager.service.IGatewayRoleDeptService;
import com.sq.partner.manager.service.IGatewayRoleMenuService;
import com.sq.partner.manager.service.IGatewayRoleService;
import com.sq.partner.manager.service.IGatewayUserService;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.StrUtil;

/**
 * 角色管理Controller
 * @author zhihuizhao
 *
 */
@Controller
@RequestMapping(value = "/systemManager")
public class GatewayRoleController {
	
	private static Logger logger = LogUtil.getLog(GatewayRoleController.class);
	
	@Resource
	private IGatewayRoleService roleService;

	@Resource
	private IGatewayRoleMenuService rmService;
	
	@Resource
	private IGatewayUserService userService;
	
	@Resource
	private IGatewayRoleDeptService rdService;
	/**
	 * 跳转至角色页面
	 * @return
	 */
	@RequestMapping(value="/roleManagement")
	public String showRoles(HttpSession session,ModelMap model){
		GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		if(user.getDepartmentStr().contains(Constants.HQ_BRANCH_CODE)){
			model.put("BRANCHCODE", true);
		}else{
			model.put("BRANCHCODE", false);
		}
		return "systemManager/roleManage";
	}
	/**
	 * 页面初始化查询所有角色
	 * @param pageIndex
	 * @param role
	 * @param roleName
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/roleManagement/initAllRoles")
	public @ResponseBody Page showUserList(HttpSession session,int pageIndex,GatewayRole role,String roleName) throws Exception
	{
		if(StrUtil.isNotEmpty(roleName)){
			role.setRoleName(roleName);
		}
		GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		Page page=new Page();
		page.setCurrent(pageIndex);
		Page p = roleService.queryPage(page, pageIndex, role,user);
		return p;
		
	}

	
	/**
	 * 在删除某角色之前，查询已有多少个用户配置该角色，给予用户友好提示
	 * @param map
	 * @param userid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/roleManagement/getUserCountOfOneRole")
	public @ResponseBody Integer getUserRoleCount(Map<String,Long> map,Long roleid) throws Exception{
		if(null!=roleid){
			map.put("roleid", roleid);
			Object obj = userService.getUserCountOfOneRole(map);
			if(obj!=null){
				List<GatewayUserRole> list = (List<GatewayUserRole>)obj;
				return list.size();
			}else{
				return 0;
			}
		}
		return 0;
	}
	
	/**
	 * 删除角色
	 * @param role
	 * @param roleid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/roleManagement/delRole")
	public @ResponseBody Result deleteRole(GatewayRole role,GatewayRoleMenu roleMenu, GatewayUserRole userRole,Long roleid) throws Exception{
		if(null!=roleid){
			roleMenu.setRoleid(roleid);
			//删除角色菜单配置
			rmService.delRoleMenusForRole(roleid);
			//删除角色机构配置
			rdService.delDeptsToOneRole(roleid);
				role.setRoleid(roleid);
				//删除角色
				roleService.deleteRole(role);
			        userRole.setRoleid(roleid);
			        //删除用户角色配置
					roleService.delUserRoleRoleid(roleid);
			return Result.success("删除角色成功");
		}else{
			return Result.fail("角色Id不能为空，无法进行删除操作");
		}
	}
	
	
	/**
	 * 增加角色
	 * @param role
	 * @param roleid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/roleManagement/addRole")
	public @ResponseBody Result addRole(HttpServletRequest req,Map<String,String> map,GatewayRole role,String roleName,String deptCode) throws Exception{
		if(StrUtil.isEmpty(roleName)){
			return Result.error("角色名称不能为空");
		}else if(roleName.length() > 10){
			return Result.error("长度不能超过10个字符");
		}else if(StrUtil.isEmpty(deptCode)){
			return Result.error("配置机构不能为空");
		}
		
		try{
			map.put("roleName", roleName);
			GatewayRole r = roleService.queryRoleNameExistsOrNot(map);
			if(r==null){
				GatewayUser user =getSessionUser(req);
				role.setRoleName(roleName);
				role.setOperUser(user.getUserid());
				role.setOperTime(getCurdate());
				role.setStatus(1);
				role.setDeptCode(deptCode);
				Long roleId = roleService.addRole(role);
				boolean flag =false;
				if(StrUtil.isNotEmpty(String.valueOf(roleId))){
					//添加角色和部门中间关系表
					GatewayRoleDept rd = new GatewayRoleDept(); 
					rd.setDeptCode(deptCode);
					rd.setRoleId(roleId);
					rd.setOperUser(getSessionUser(req).getUserid());
					rd.setOperTime(getCurdate());
					rd.setStatus("1");
					flag = rdService.addDeptsToOneRole(rd);
				}
 				if(flag){
					return Result.success("添加角色成功");
				}else{
					return Result.error("添加角色失败");
				}
			}else{
				return Result.error("该角色名已存在，请重新输入");
			}
		}catch(Exception e){
			logger.info("系统错误",e);
			throw new AppException("系统错误");
		}
	}
	
	
	
	/**
	 * 修改角色
	 * @param role
	 * @param roleid
	 * @param roleName
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/roleManagement/modifyRole")
	public @ResponseBody Result modifyRole(HttpServletRequest req,GatewayRole role,Long roleid,String roleName,String deptCode) throws Exception {
		if(StrUtil.isEmpty(roleName)){
			return Result.error("角色名称不能为空");
		}else if(roleName.length() > 10){
			return Result.error("长度不能超过10个字符");
		}else if(StrUtil.isEmpty(deptCode)){
			return Result.error("配置机构不能为空");
		}
		
		role.setRoleid(roleid);
		role.setRoleName(roleName);
		role.setOperTime(getCurdate());
		role.setOperUser(((GatewayUser)getSessionUser(req)).getUserid());
		boolean flag = roleService.modifyRole(role);
		GatewayRoleDept rd = new GatewayRoleDept(); 
		rd.setDeptCode(deptCode);
		rd.setRoleId(roleid);
		rd.setOperUser(getSessionUser(req).getUserid());
		rd.setOperTime(getCurdate());
		boolean deptFlag = rdService.updateRoleDeptInfo(rd);
		if(flag || deptFlag){
			return Result.success("修改成功");
		}else{
			return Result.error("修改失败");
		}
	}
	
	
	
	/**
	 * 给角色绑定菜单
	 * @param roleid    角色id
	 * @param menuidStr 菜单ID 字符串
	 * @return
	 */
	@RequestMapping(value="/roleManagement/bindMenusToRole")
	public @ResponseBody Result bindMenuToRole(HttpServletRequest req,GatewayRoleMenu roleMenu,Long roleid,String menuidStr) throws Exception{
		
		if(roleid!=null){
			if(StrUtil.isNotEmpty(menuidStr)){
				//删除该角色下所有菜单
				rmService.delRoleMenusForRole(roleid);
					String [] menuidArr = menuidStr.split(",");
					//循环添加菜单
					for(int i=0;i<menuidArr.length;i++){
						GatewayRoleMenu rm = new GatewayRoleMenu();
						rm.setMenuid(Long.parseLong(menuidArr[i]));
						rm.setRoleid(roleid);
						rm.setOperTime(getCurdate());
						rm.setOperUser(((GatewayUser)getSessionUser(req)).getUserid());
						rmService.addMenusForRole(rm);
					}
					return Result.success("配置菜单成功");
				
			}else{
//				rmService.delMenusForRole(roleMenu);
//				return Result.success("配置成功，该角色下暂无菜单");
				return Result.error("请选择一个菜单");
			}
		}else{
			return Result.fail("系统无法找到该角色");
		}
	}
	
	
	
	/**
	 * 查询某角色下所有菜单
	 * @param menuid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/roleManagement/queryAllMenusForCurRole")
	public @ResponseBody List<GatewayRoleMenu> queryAllMenus(GatewayRoleMenu rm,Long roleid) throws Exception{
		rm.setRoleid(roleid);
		List<GatewayRoleMenu> list = rmService.queryAllMenusOfCurRole(rm);
			return list;
	}
	
	
	
	/**
	 * 给某个角色配置权限机构
	 * @param req
	 * @param roleMenu
	 * @param roleid
	 * @param deptIdStr
	 * @return
	 * @throws Exception
	 *//*
	@RequestMapping(value="/roleManagement/bindDeptsToRole")
	public @ResponseBody Result bindDeptToRole(HttpServletRequest req,Long roleid,String deptIdStr) throws Exception{
		if(null==roleid){
			return Result.error("角色ID不能为空");
		}
		if(StrUtil.isNotEmpty(deptIdStr)){
			//每次配置机构之前，删除该角色所有机构配置
			rdService.delDeptsToOneRole(roleid);
			
			String dpidArr[] = deptIdStr.split(",");
			for(int i=0;i<dpidArr.length;i++){
				GatewayRoleDept rd = new GatewayRoleDept(); 
				rd.setDeptCode(dpidArr[i]);
				rd.setRoleId(roleid);
				rd.setOperUser(getSessionUser(req).getUserid());
				rd.setOperTime(getCurdate());
				rd.setStatus("1");
				rdService.addDeptsToOneRole(rd);
			}
			return Result.success("权限机构配置成功");
		}else{
//			rdService.delDeptsToOneRole(rdp);
//			return Result.success("重置成功，当前角色暂无机构配置");
			return Result.error("请选择一个机构");
		}
	}
	*/
	
	/**
	 * 在当前登录用户的权限机构里，获取某个角色所配置的机构
	 * @param req
	 * @param roleId
	 * @return
	 * @throws Exception
	 *//*
	@RequestMapping(value="/roleManagement/getDeptsOfCurRole")
	public @ResponseBody List<DeptDto> queryDeptsOfcurUser(HttpServletRequest req,Long roleId) throws Exception{
		if(null!=roleId){
			List<DeptDto> list = rdService.queryDeptDtobyRoleId(roleId);
			GatewayUser user = getSessionUser(req);
			return list;
		}
		return null;
	}*/
	
	
	/**
	 * 查询权限机构，只控制到分公司
	 * @param req
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/roleManagement/getBranchDepts")
	public @ResponseBody Page<CoreDept> queryBranchDepts(HttpServletRequest req, CoreDept cd, int pageIndex) throws Exception {
		GatewayUser user = getSessionUser(req);
		Page<CoreDept> page = new Page<CoreDept>();
		page.setType(cd);
		page.setCurrent(pageIndex);
		return  rdService.queryDeptOfOneUser(page,user);
	}
	
	
	/**
	 * 获取系统当前时间
	 * @return
	 * @throws Exception
	 */
	public static Date getCurdate() throws Exception{
		Date dt = new Date();
		return dt;
	}
	
	/**
	 * 获取session中的User
	 * @param req
	 * @return
	 */
	public static GatewayUser getSessionUser(HttpServletRequest req){
		HttpSession session = req.getSession();
		GatewayUser u = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		return u;
	}
	
}
